import datetime
import pprint
import util
import sqlalchemy as sql
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

import util
engine = sql.create_engine('sqlite:///saModel_3.db', echo=False)
# Base = sql.ext.declarative.declarative_base()
Base = declarative_base()

class User(Base):
    __module__ = __name__
    __tablename__ = 'users'
    nbr = sql.Column('nbr', sql.Integer, primary_key=True)
    id = sql.Column('id', sql.Text, unique=True)
    email = sql.Column('email', sql.Text)
    name_first = sql.Column('name_first', sql.Text)
    name_last = sql.Column('name_last', sql.Text)
    password_hash = sql.Column('password_hash', sql.Text)

    def __init__(self, id, email, name_first, name_second, name_last, password):
        self.id = id
        self.email = email
        self.name_first = name_first
        self.name_last = name_last
        self.password_hash = util.encrypt(password)

    def __repr__(self):
        #TODO upgrade to python 2.6
        return '<User {0}: {1}>'.format(self.nbr, self.id)

users_table = User.__table__
metadata = Base.metadata

def create_user(id, email, name_first, name_last, password):
    Session = sessionmaker(bind=engine, autoflush=True, autocommit=False)
    session = Session()
    u = User(id, email, name_first, name_last, password, password)
    session.add(u)
    session.commit()

def list_users():
    Session = sessionmaker(bind=engine, autoflush=True, autocommit=True)
    session = Session()
    return session.query(User).all()

if (__name__ == '__main__'):  
#===============================================================================
#    # use this to create the db
#    metadata.create_all(engine)
#===============================================================================
    unique = util.unique_id()
    # unique = ''
    create_user('id_' + unique, 'Frederick', 'Smith', 
                          'fred@g.com', 'secret')
    unique = util.unique_id()
    create_user('id_' + unique, 'Frederick', 'Smith', 
                          'fred@g.com', 'secret')
    pprint.pprint(list_users())